<template>
  <div class='page'>
    <van-nav-bar :title='$t("m.header.carts")' fixed>
      <van-icon v-if='carts.length' slot='right' :info='editText' :class='{ editing: showEdit }' @click='onEdit' />
    </van-nav-bar>
    <div class='container'>
      <nopage ref='nopage' :title='title' path='/cart' />
      <div>
        <van-swipe-cell v-for='(cartItem, cartIndex) in carts' :key='cartIndex' :right-width='65' :on-close='onClose'
                        :data_id='cartItem' :data_index='cartIndex'
        >
          <div class='cart-item flex-space' :class='{ selected: itemIndex === cartIndex }'>
            <div class='flex'>
              <van-checkbox v-model='cartItem.goodsRadio' @change='onGoodsRadio(cartItem)' />
              <img v-lazy='cartItem.imgCover' class='goods-img' @click.stop='onDetail(cartItem._id)'>
              <div class='goods-textBox' @click.stop='onDetail(cartItem._id)'>
                <p class='product_title'>
                  {{ cartItem.title }}
                </p>
                <div class='goodsOp flex'>
                  <van-icon name='diamond-o' @click.stop='onCutCart(cartItem, cartIndex)' />
                  <input type='text' :value='cartItem.num'>
                  <van-icon name='add-o' @click.stop='onAddCart(cartItem, cartIndex)' />
                </div>
                <p class='product_price'>
                  ¥{{ cartItem.priceNow }}
                </p>
              </div>
            </div>
            <van-icon v-show='showEdit' class='remove' name='delete' color='#f44' @click.stop='onRemove(cartItem, cartIndex)'/>
          </div>
          <span slot='right' class='delete-btn'>删除</span>
        </van-swipe-cell>
      </div>
    </div>
    <template v-if='showEdit'>
      <van-submit-bar class='footer-bottom' suffix-label='' button-text='删除' :disabled='!deleteAll'
                      @submit='handleDeleteAll'
      >
        <van-checkbox v-model='goodsRadioAll' @click='onDeleteAll'>
          全选
        </van-checkbox>
      </van-submit-bar>
    </template>
    <template v-else>
      <van-submit-bar v-if='show && carts.length && show' class='footer-bottom' :price='allCoach' :button-text='$t("m.carts.submitOrder")' @submit='onOrder'>
        <van-checkbox v-model='goodsRadioAll' @click='onSelectAll'>
          全选
        </van-checkbox>
      </van-submit-bar>
    </template>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapActions, mapState } from 'vuex'
import { dataMixin } from '@/mixins/dataMixin.js'
import { apiUpdateCart } from '@/api/cart.js'
import { NavBar, Checkbox, CheckboxGroup, SubmitBar, Icon, Dialog, SwipeCell, Toast } from 'vant'
export default {
  metaInfo () {
    return {
      title: this.$t('m.meta.cart.title'),
      meta: [
        {
          name: this.$t('m.meta.cart.name'),
          content: this.$t('m.meta.cart.content'),
        },
      ],
    }
  },
  activated () {
    console.log(57577575)
  },
  beforeMount () {
    console.log(2222222)
    this.getCart()
  },
  mounted () {
    console.log('xxx111')
  },
  beforeRouteEnter (to, from, next) {
    next(() => {
      console.log(1)
    })
  },
  data () {
    return {
      goodsRadioAll: false,
      allCoach: 0,
      radioArr: [],
      itemIndex: '',
      checked: true,
      showEdit: false,
      show: false,
      editText: '编辑',
      deleteAll: false,
    }
  },
  mixins: [dataMixin],
  components: {
    [NavBar.name]: NavBar,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [SubmitBar.name]: SubmitBar,
    [Icon.name]: Icon,
    [Dialog.name]: Dialog,
    [SwipeCell.name]: SwipeCell,
    [Toast.name]: Toast,
  },
  computed: {
    ...mapState(['carts']),
  },
  watch: {
    carts (val) {
      console.log(val)
      if (val && !val.length) {
        this.title = this.$t('m.carts.noCarts')
        this.$refs.nopage.onDisplay()
      }
    },
    showEdit (val) {

    },
  },
  methods: {
    ...mapActions(['getCartList', 'deleteCartGoods', 'setData']),
    onClose (clickPosition, instance, cartItem, cartIndex) {
      switch (clickPosition) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close()
          break
        case 'right':
          console.log(cartItem)
          console.log(clickPosition)
          console.log(cartIndex)
          Dialog.confirm({
            message: '确定删除吗？',
          }).then(() => {
            instance.close()
            this.sureRemove(instance.$attrs.data_id, instance.$attrs.data_index)
          })
          break
      }
    },
    getRef (index) {
      return `cell${index}`
    },
    getCart () {
      this.getCartList().then(res => {
        if (res.code == -1) {
          this.title = this.$t('m.login.noLogin')
          setTimeout(() => {
            this.$refs.nopage.onDisplay()
            this.$refs.nopage.onLogin()
          }, 300)
          return
        }
        this.show = true
        const carts = res.result
        if (carts.length == 0) {
          this.title = this.$t('m.carts.noCarts')
          this.$refs.nopage.onDisplay()
        } else {
          carts.map(item => {
            typeof item.goodsRadio == 'undefined' && this.$set(item, 'goodsRadio', false)
          })
        }
      })
    },
    onGoodsRadio () {
      this.radioArr = []
      this.carts.forEach(itemGoods => {
        this.radioArr.push(itemGoods.goodsRadio)
      })
      this.radioArr.indexOf(false) == -1 ? (this.goodsRadioAll = true) : (this.goodsRadioAll = false)
      this.onCalAllCoach()
    },
    handleDeleteAll () {
      console.log(1111)
      if (!this.carts.length) return
      Toast.success({
        message: '后台删除功能待开发',
        duration: 3000,
      })
    },
    onDeleteAll () {
      !this.goodsRadioAll
        ? this.carts.forEach(item => {
          item.goodsRadio = true
        })
        : this.carts.forEach(item => {
          item.goodsRadio = false
        })
      this.deleteAll = true
    },
    onSelectAll () {
      !this.goodsRadioAll
        ? this.carts.forEach(item => {
          item.goodsRadio = true
        })
        : this.carts.forEach(item => {
          item.goodsRadio = false
        })
      this.onCalAllCoach()
    },
    async onAddCart (item, cartIndex) {
      await apiUpdateCart(item._id, 'add')
      item.num++
      Vue.set(this.carts, cartIndex, item)
      this.onCalAllCoach()
    },
    async onCutCart (item, cartIndex) {
      if (item.num > 1) {
        await apiUpdateCart(item._id, 'cut')
        item.num--
        Vue.set(this.carts, cartIndex, item)
        this.onCalAllCoach()
      }
    },
    onCalAllCoach () {
      this.allCoach = 0
      this.carts.forEach(item => {
        item.goodsRadio && (this.allCoach += item.num * item.priceNow)
      })
      this.allCoach = this.allCoach * 100
    },
    onRemove (item, index) {
      Dialog.confirm({
        message: '确定删除',
      }).then(() => {
        this.deleteCartGoods({
          item,
          index,
        })
      })
    },
    /* 提交订单 */
    onOrder () {
      let orderArr = []
      this.carts.forEach(item => {
        item.goodsRadio && orderArr.push(item)
      })
      if (orderArr.length) {
        this.$router.push({
          path: 'orderwait',
          query: {
            status: 'todo',
          },
        })
        this.setData({
          orders: orderArr,
        })
      }
    },
    onEdit () {
      this.showEdit = !this.showEdit
      if (this.showEdit) {
        this.editText = '完成'
      } else {
        this.editText = '编辑'
      }
    },
    /* 进入商品详情 */
    onDetail (id) {
      this.$router.push({
        path: '/detail',
        query: {
          id: id,
        },
      })
    },
  },
}
</script>
<style lang='scss' scoped>
.container {
  padding-top: 46px;
  padding-bottom: 90px;

  :global(.van-swipe-cell__right) {
    width: 65px;
    background-color: #e14628;
  }
  :global(.van-checkbox__icon--checked .van-icon) {
    border-color: #f44;
    background-color: #f44;
  }
}
.footer-bottom {
  :global(.van-checkbox__icon--checked .van-icon) {
    border-color: #f44;
    background-color: #f44;
  }
}
:global(.van-info) {
  background-color: #fff;
  color: #7d7e80;
  cursor: pointer;
  width: 60px;
  font-size: 16px;
  right: 15px;
  top: -12px;
  line-height: 1.4;
}
:global(.van-icon.editing) {
  .van-info {
    color: #fa0e25;
  }
}
:global(.van-icon-edit) {
  cursor: pointer;
}
:global(.van-checkbox) {
  cursor: pointer;
}
:global(.van-icon-delete) {
  cursor: pointer;
}
.delete-btn {
  display: inline-block;
  width: 100%;
  background-color: #e14628;
  text-align: center;
  margin-top: 48px;
  color: #fff;
}
.cart-item {
  height: 120px;
  padding: 0 10px;
  background: white;
}
.goods-img {
  margin-right: 10px;
  width: 100px;
  height: 100px;
  margin-left: 10px;
}
.goods-coach {
  color: red;
  align-self: flex-end;
}
.goodsOp {
  margin: 20px 0;
  input {
    border: none;
    font-size: 12px;
    text-align: center;
    width: 30px;
  }
}
.cartBottom-detail {
  line-height: 60px;
  font-size: 14px;
  width: 100%;
  position: absolute;
  bottom: 40px;
  padding-left: 10px;
  box-sizing: border-box;
  color: $theme_color;
  background: white;
  border-top: 1px solid #ccc;
}
.subminCart {
  padding-right: 20px;
}
.van-submit-bar {
  bottom: 50px;
}
.van-submit-bar__bar {
  padding-left: 10px;
}
</style>
